package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Dao.ChargeDetailRepository;
import com.realtyManage.springboot.Model.Do.ChargeDetail;
import com.realtyManage.springboot.Model.Do.Customer;
import com.realtyManage.springboot.Model.Do.HouseDetail;
import com.realtyManage.springboot.Model.Do.User;
import com.realtyManage.springboot.Model.Vo.ChargeDetailEntity;
import com.realtyManage.springboot.Service.IChargeDetailService;
import com.realtyManage.springboot.Service.ICustomerService;
import com.realtyManage.springboot.Service.IIndexService;
import com.realtyManage.springboot.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * ChargeDetailServiceImpl
 *
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/5/5
 **/
@Service
@Transactional
public class ChargeDetailServiceImpl implements IChargeDetailService{
    @Autowired
    private ChargeDetailRepository chargeDetailRepository;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IIndexService indexService;

    @Override
    public void addNewRecord(Integer custId, Double realMoney,Integer type) {
        Customer customer = customerService.getCustomerDetail(custId);
        //HouseDetail houseDetail = indexService.getHouseDetail(customer.getConnHouseId());
        User user = userService.findById(customer.getConnUserId());//客户对应经纪人信息

        Double money = this.calculateMony(custId,realMoney);

        ChargeDetail chargeDetail = new ChargeDetail();
        chargeDetail.setConnCustId(custId);
        chargeDetail.setConnHouseId(indexService.getHouseDetail(customer.getConnHouseId()).getId());

        //若为精确报备需扣除平台分成
        if(customer.getType()==1){
            Double platformMoney = money*customer.getPlatformRate()/100;
            money = money - platformMoney;
            chargeDetail.setRemark("扣除平台佣金分成："+platformMoney);
        }

        if(type==1){//房款提成-给当前用户
            chargeDetail.setConnUserId(user.getId());
        }else if(type==2){//下线提成-给门店经纪人
            chargeDetail.setConnUserId(user.getUpId());
            money = money * customer.getChargeRate()/100;
        }else if(type==3){//门店提成-门店经纪人成交就有
            type = 2;
            chargeDetail.setConnUserId(user.getUpId());
            money = realMoney*customer.getShopChargeRate()/100+customer.getShopChargeFixed();
        }

        chargeDetail.setRealMoney(money);
        chargeDetail.setType(type);
        chargeDetail.setSettleState(1);
        chargeDetail.setState(1);

        chargeDetailRepository.save(chargeDetail);
    }

    @Override
    public void updateRecord(Integer custId,Integer settleState,Integer state) {
        Customer customer = customerService.getCustomerDetail(custId);
        HouseDetail houseDetail = indexService.getHouseDetail(customer.getConnHouseId());
        ChargeDetail chargeDetail = chargeDetailRepository.findByConnHouseIdAndConnCustId(houseDetail.getId(),custId);
        if(settleState != null){
            chargeDetail.setSettleState(settleState);
        }
        if(state != null){
            chargeDetail.setState(state);
        }
        chargeDetailRepository.save(chargeDetail);
    }

    @Override
    public List<ChargeDetail> findPagedByWhereClause(ChargeDetailEntity chargeDetailEntity) {
        Integer pageNumber = chargeDetailEntity.getPageNumber()-1;
        Integer pageSize = chargeDetailEntity.getPageSize();

        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(chargeDetailEntity.getSort() != null){
            if (chargeDetailEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, chargeDetailEntity.getSortField());
            } else if(chargeDetailEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, chargeDetailEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<ChargeDetail> specification = (Specification<ChargeDetail>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (chargeDetailEntity.getUid()!=null) {
                // 根据经纪人id查询
                Predicate p1 = criteriaBuilder.equal(root.get("connUserId"),chargeDetailEntity.getUid());
                list.add(p1);
            }
            if (chargeDetailEntity.getHouseId()!=null) {
                // 根据楼盘id查询
                Predicate p2 = criteriaBuilder.equal(root.get("connHouseId"),chargeDetailEntity.getHouseId());
                list.add(p2);
            }
            if (chargeDetailEntity.getSettleState()!=null) {
                // 根据佣金状态查询：1.未结算 2.已结算
                Predicate p3 = criteriaBuilder.equal(root.get("settleState"),chargeDetailEntity.getSettleState());
                list.add(p3);
            }
            if (chargeDetailEntity.getState()!=null) {
                // 根据记录状态查询：1.有效 2.无效
                Predicate p4 = criteriaBuilder.equal(root.get("state"),chargeDetailEntity.getState());
                list.add(p4);
            }
            if (chargeDetailEntity.getType()!=null) {
                // 根据客户状态id查询
                Predicate p5 = criteriaBuilder.equal(root.get("type"),chargeDetailEntity.getType());
                list.add(p5);
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return chargeDetailRepository.findAll(specification, pageable).getContent();
    }

    /*
    * @Author Danny
    * @Description //计算经纪人实际佣金
    * @Date 2019/5/8
    * @Param [custId, realMoney]
    * @Return java.lang.Double
    **/
    public Double calculateMony(int custId ,double realMoney){
        Customer customer = customerService.getCustomerDetail(custId);
        //HouseDetail houseDetail = indexService.getHouseDetail(customer.getConnHouseId());
        User user = userService.findById(customer.getConnUserId());//客户对应经纪人信息

        Double shopChargeRate = (customer.getShopChargeRate()!=null?customer.getShopChargeRate()/100:0.00);
        Double shopChargeFixed = (customer.getShopChargeFixed()!=null?customer.getShopChargeFixed():0.00);
        String shopChargeExtra = (customer.getShopChargeExtra()!=null?customer.getShopChargeExtra():"");

        Double personChargeRate = (customer.getPersonChargeRate()!=null?customer.getPersonChargeRate()/100:0.00);
        Double personChargeFixed = (customer.getPersonChargeFixed()!=null?customer.getPersonChargeFixed():0.00);
        String personChargeExtra = (customer.getPersonChargeExtra()!=null?customer.getPersonChargeExtra():"");

        Double indChargeRate = (customer.getIndChargeRate()!=null?customer.getIndChargeRate()/100:0.00);
        Double indChargeFixed = (customer.getIndChargeFixed()!=null?customer.getIndChargeFixed():0.00);
        String indChargeExtra = (customer.getIndChargeExtra()!=null?customer.getIndChargeExtra():"");


        Double money = 0.00;
        if(user.getLevel()==4){//门店负责人
            money = realMoney*shopChargeRate/100+shopChargeFixed;
        }else if(user.getLevel()==3){//门店经纪人
            money = realMoney*personChargeRate/100+personChargeFixed;
        }else if(user.getLevel()==2){//独立经纪人
            money = realMoney*indChargeRate/100+indChargeFixed;
        }

        return money;
    }
}
